<template>
	<view class="page-main">
		<u--form ref="uForm" :model="timeLineForm" :rules="rules" labelPosition="top" labelWidth="auto">
			<u-form-item label="日期时间：" prop="formatDateTime" borderBottom required @click="showPicker=true">
				<u--input v-model="timeLineForm.formatDateTime" placeholder="请选择日期时间" border="none" disabled
					disabledColor="#ffffff" />
				<u-icon slot="right" name="arrow-right" />
			</u-form-item>
			<u-form-item label="内容：" prop="content" borderBottom required>
				<view class="content">
					<textarea v-model="timeLineForm.content" placeholder="请输入内容" maxlength="256" border="none"
						style="width: 100%;" />
				</view>
				<view class="content-images">
					<u-upload :fileList="fileList" width="200rpx" height="200rpx" accept="media" uploadText="图片/视频"
						maxCount="9" multiple @afterRead="fileSelect" @delete="fileDelete" />
				</view>
			</u-form-item>
		</u--form>

		<view style="margin-top: 80rpx;">
			<u-button type="success" text="提交" @click="onSubmit()" />
		</view>

		<u-datetime-picker ref="datetimePicker" :show="showPicker" v-model="selectDate" :formatter="formatter"
			title="选择日期时间" closeOnClickOverlay :minDate="minDate" :maxDate="newDate" @close="showPicker=false"
			@cancel="showPicker=false" @confirm="pickerConfirm" />
	</view>
</template>

<script>
	export default {
		data() {
			return {
				isEdit: false,
				showPicker: false,
				selectDate: new Date(),
				minDate: new Date("1971").getTime(),
				newDate: new Date().getTime(),
				timeLineForm: {
					dateTime: null,
					formatDateTime: null,
					content: null,
					images: null
				},
				fileList: [],
				deletedImage: [],
				rules: {
					formatDateTime: {
						type: 'string',
						required: true,
						message: '请选择日期时间',
						trigger: ['blur', 'change']
					},
					content: {
						type: 'string',
						required: true,
						message: '请输入内容',
						trigger: ['blur', 'change']
					},
				}
			}
		},
		onLoad(option) {
			if (option.id) {
				this.isEdit = true;
				const db = uniCloud.database()
				db.collection('time_line')
					.doc(option.id).get({
						getOne: true
					}).then((res) => {
						this.timeLineForm = res.result.data
						this.timeLineForm.formatDateTime = uni.$u.timeFormat(this.timeLineForm.dateTime,
							'yyyy年mm月dd日 hh时MM分');
						this.fileList = this.timeLineForm.images

					}).catch((err) => {
						console.log(err);
					})
			}

		},
		methods: {
			fileSelect(e) {
				let imageMax = 150 * 1024,
					videoMax = 50 * 1024 * 1024,
					isExceedMax = false
				for (let i = 0; i < e.file.length; i++) {
					let item = e.file[i]
					if ((item.type === "image" && item.size <= imageMax) ||
						(item.type === "video" && item.size <= videoMax)) {
						if (item.type === "video") {
							item.poster = item.thumb
						}
						delete item.thumb
						this.fileList.push(item)
						continue
					}
					isExceedMax = true
				}
				if (isExceedMax) {
					uni.$u.toast(`文件过大，请压缩后上传`);
				}

			},
			onSubmit() {
				if (this.$tools.getUser().state == 0) {
					uni.$u.toast('请先绑定伴侣');
					return;
				}

				this.$refs.uForm.validate().then(async (res) => {
					uni.showLoading({
						title: '操作中',
						mask: true
					});
					if (this.fileList.length > 0) {
						let isSuccess = true
						await this.uploadFile(this.fileList).catch((err) => {
							isSuccess = false
							uni.hideLoading();
							uni.$u.toast('上传失败：' + err.message)
						})
						if (!isSuccess) {
							return
						}
					}
					this.uploadSuccess(this.fileList);
				}).catch(err => {
					uni.$u.toast('校验失败')
				})
			},
			uploadSuccess(files) {
				let pages = getCurrentPages(),
					prevPage = pages[pages.length - 2],
					timeLineForm = this.timeLineForm
				if (files.length > 0) {
					timeLineForm.images = files
				}
				const db = uniCloud.database()
				if (this.isEdit) {
					if (this.deletedImage.length > 0) {
						uniCloud.callFunction({
							name: 'deleteFile',
							data: {
								fileList: this.deletedImage
							}
						})
					}

					let timeLineId = timeLineForm._id
					delete timeLineForm._id
					delete timeLineForm.formatDateTime
					db.collection('time_line')
						.doc(timeLineId).update(timeLineForm)
						.then((res) => {
							timeLineForm._id = timeLineId
							uni.hideLoading();
							uni.$u.toast('修改成功');

							uni.navigateBack({
								success: () => {
									let list = prevPage.$vm.list
									let index = list.findIndex(item => item._id === timeLineId)
									list.splice(index, 1, timeLineForm)
								}
							});
						}).catch((err) => {
							uni.hideLoading();
							uni.$u.toast(err.message);
						})

					return;
				}

				//添加
				delete timeLineForm.formatDateTime
				timeLineForm.partnerConfigId = this.$tools.getUser().configId
				timeLineForm.author = this.$tools.getUser().nickName
				db.collection('time_line')
					.add(timeLineForm)
					.then((res) => {
						timeLineForm._id = res.result.id
						uni.hideLoading();
						uni.$u.toast('添加成功');

						uni.navigateBack({
							success: () => {
								prevPage.$vm.currentPage = 0
								prevPage.$vm.list = []
								prevPage.$vm.totalData = 1
								prevPage.$vm.onList()
							}
						})
					}).catch((err) => {
						uni.hideLoading();
						uni.$u.toast(err.message);
					})
			},
			fileDelete(e) { //文件删除时
				if (e.file.url.indexOf('://tmp') === -1) {
					this.deletedImage.push(e.file.url)
					if (e.file.type === 'video') this.deletedImage.push(e.file.poster)
				}
				this.fileList.splice(e.index, 1)
			},
			async uploadFile(fileArr) {
				let newDate,
					imgType,
					fileType,
					file
				for (let i = 0; i < fileArr.length; i++) {
					file = fileArr[i]
					if (file.url.indexOf('://tmp') === -1) { //线上地址不用上传
						continue
					}
					newDate = new Date().getTime()
					fileType = file.type
					if (fileType === 'video') {
						imgType = file.poster.split(".")
						imgType = imgType[imgType.length - 1]
						const res = await uniCloud.uploadFile({
							filePath: file.poster,
							cloudPath: 'timeline_' + fileType + '_poster_' + newDate + '_' + i + '.' + imgType,
							fileType: 'image'
						})
						file.poster = res.fileID
					}
					imgType = file.url.split(".")
					imgType = imgType[imgType.length - 1]
					const res = await uniCloud.uploadFile({
						filePath: file.url,
						cloudPath: 'timeline_' + fileType + '_' + newDate + '_' + i + '.' + imgType,
						fileType: fileType
					})
					file.url = res.fileID
				}

				return true
			},
			pickerConfirm(e) {
				let timeStamp = new Date(e.value).getTime()
				this.timeLineForm.formatDateTime = uni.$u.timeFormat(timeStamp, 'yyyy年mm月dd日 hh时MM分');
				this.timeLineForm.dateTime = timeStamp;
				this.showPicker = false;
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				} else if (type === 'month') {
					return `${value}月`
				} else if (type === 'day') {
					return `${value}日`
				} else if (type === 'hour') {
					return `${value}时`
				} else if (type === 'minute') {
					return `${value}分`
				}
				return value
			},
		}
	}
</script>

<style>
	page {
		--bg-image: none;
	}

	.content {
		font-size: 15px;
		color: #606266;
		padding: 9px;
	}

	.u-upload__deletable.data-v-69e2a36e {
		width: 20px !important;
		height: 20px !important;
	}

	.u-upload__deletable.data-v-69e2a36e text {
		font-size: 15px !important;
		line-height: 15px !important;
	}
</style>